<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'

const props = withDefaults(defineProps<Props>(), {
  config: null,
})

const emit = defineEmits<Emits>()

interface Props {
  modelValue: boolean
  config?: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

// 表单引用
const formRef = ref()
const submitting = ref(false)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

const isEdit = computed(() => !!props.config?.id)

// 表单数据
const form = reactive({
  name: '',
  description: '',
  is_default: false,
  service_type: 'DI',
  office_codes: ['HKLO'],
  time_ranges: ['09:00', '10:00', '14:00', '15:00'],
  date_range_days: 70,
  max_attempts: 3,
  enable_placeholder: false,
  placeholder_ratio: 0.2,
  auto_release_hours: 24,
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
  ],
  service_type: [
    { required: true, message: '请选择服务类型', trigger: 'change' },
  ],
  office_codes: [
    { required: true, message: '请选择至少一个办理地点', trigger: 'change' },
  ],
  time_ranges: [
    { required: true, message: '请选择至少一个时间段', trigger: 'change' },
  ],
  date_range_days: [
    { required: true, message: '请设置日期范围', trigger: 'blur' },
    { type: 'number', min: 1, max: 90, message: '日期范围应在1-90天之间', trigger: 'blur' },
  ],
  max_attempts: [
    { required: true, message: '请设置最大尝试次数', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '最大尝试次数应在1-10次之间', trigger: 'blur' },
  ],
  placeholder_ratio: [
    { type: 'number', min: 0.1, max: 1.0, message: '占号比例应在0.1-1.0之间', trigger: 'blur' },
  ],
  auto_release_hours: [
    { type: 'number', min: 1, max: 168, message: '自动释放时间应在1-168小时之间', trigger: 'blur' },
  ],
}

// 监听config变化
watch(() => props.config, (newVal) => {
  if (newVal) {
    // 编辑模式，填充表单
    Object.assign(form, {
      name: newVal.name || '',
      description: newVal.description || '',
      is_default: newVal.is_default || false,
      service_type: newVal.service_type || 'DI',
      office_codes: parseJsonArray(newVal.office_codes) || ['HKLO'],
      time_ranges: parseJsonArray(newVal.time_ranges) || ['09:00', '10:00', '14:00', '15:00'],
      date_range_days: newVal.date_range_days || 30,
      max_attempts: newVal.max_attempts || 3,
      enable_placeholder: newVal.enable_placeholder || false,
      placeholder_ratio: newVal.placeholder_ratio || 0.2,
      auto_release_hours: newVal.auto_release_hours || 24,
    })
  }
  else {
    // 新建模式，重置表单
    resetForm()
  }
})

// 重置表单
function resetForm() {
  Object.assign(form, {
    name: '',
    description: '',
    is_default: false,
    service_type: 'DI',
    office_codes: ['HKLO'],
    time_ranges: ['09:00', '10:00', '14:00', '15:00'],
    date_range_days: 30,
    max_attempts: 3,
    enable_placeholder: false,
    placeholder_ratio: 0.2,
    auto_release_hours: 24,
  })

  // 清除验证错误
  formRef.value?.clearValidate()
}

// 关闭对话框
function handleClose() {
  visible.value = false
  resetForm()
}

// 提交表单
async function handleSubmit() {
  try {
    // 验证表单
    await formRef.value?.validate()

    submitting.value = true

    // 准备提交数据（深拷贝为可结构化克隆的纯对象）
    const submitData = JSON.parse(JSON.stringify({
      name: form.name,
      description: form.description,
      is_default: form.is_default,
      service_type: form.service_type,
      office_codes: form.office_codes,
      time_ranges: form.time_ranges,
      date_range_days: form.date_range_days,
      max_attempts: form.max_attempts,
      enable_placeholder: form.enable_placeholder,
      placeholder_ratio: form.placeholder_ratio,
      auto_release_hours: form.auto_release_hours,
    }))

    // 调用API
    let response
    if (isEdit.value) {
      response = await window.api.quickBooking.updateConfig(props.config.id, submitData)
    }
    else {
      response = await window.api.quickBooking.createConfig(submitData)
    }

    if (response.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    }
    else {
      ElMessage.error(response.error || (isEdit.value ? '更新失败' : '创建失败'))
    }
  }
  catch (error) {
    if (error !== 'validation-failed') {
      console.error('配置提交失败:', error)
      ElMessage.error('操作失败')
    }
  }
  finally {
    submitting.value = false
  }
}

// 工具函数
function parseJsonArray(jsonStr) {
  try {
    return JSON.parse(jsonStr || '[]')
  }
  catch {
    return []
  }
}

function formatPercentage(value) {
  return `${(value * 100).toFixed(0)}%`
}
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑快速预约配置' : '新建快速预约配置'"
    width="700px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      @submit.prevent
    >
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入配置名称" />
      </el-form-item>

      <el-form-item label="配置描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="2"
          placeholder="请输入配置描述（可选）"
        />
      </el-form-item>

      <el-form-item label="是否默认配置" prop="is_default">
        <el-switch v-model="form.is_default" />
        <div class="form-tip">
          设为默认配置后，其他配置的默认状态将被取消
        </div>
      </el-form-item>

      <el-form-item label="服务类型" prop="service_type">
        <el-select v-model="form.service_type" placeholder="选择服务类型">
          <el-option label="驾照换证 (DI)" value="DI" />
          <el-option label="其他服务" value="OTHER" />
        </el-select>
      </el-form-item>

      <el-form-item label="办理地点" prop="office_codes">
        <el-select
          v-model="form.office_codes"
          multiple
          placeholder="选择办理地点，可多选"
        >
          <el-option label="香港牌照事务处 (HKLO)" value="HKLO" />
          <el-option label="九龙牌照事务处 (KLO)" value="KLO" />
          <el-option label="观塘牌照事务处 (KTO)" value="KTO" />
          <el-option label="沙田牌照事务处 (STO)" value="STO" />
          <el-option label="元朗牌照事务处 (YLO)" value="YLO" />
        </el-select>
        <div class="form-tip">
          选择多个地点可以增加预约成功率
        </div>
      </el-form-item>

      <el-form-item label="偏好时间" prop="time_ranges">
        <el-select
          v-model="form.time_ranges"
          multiple
          placeholder="选择偏好时间，可多选"
        >
          <el-option label="09:00" value="09:00" />
          <el-option label="10:00" value="10:00" />
          <el-option label="11:00" value="11:00" />
          <el-option label="12:00" value="12:00" />
          <el-option label="14:00" value="14:00" />
          <el-option label="15:00" value="15:00" />
          <el-option label="16:00" value="16:00" />
          <el-option label="17:00" value="17:00" />
        </el-select>
        <div class="form-tip">
          建议选择多个时间段，提高预约成功率
        </div>
      </el-form-item>

      <el-form-item label="日期范围" prop="date_range_days">
        <el-input-number
          v-model="form.date_range_days"
          :min="1"
          :max="90"
          placeholder="天数"
        />
        <div class="form-tip">
          从明天开始计算的天数，建议30天以内
        </div>
      </el-form-item>

      <el-form-item label="最大尝试次数" prop="max_attempts">
        <el-input-number
          v-model="form.max_attempts"
          :min="1"
          :max="10"
          placeholder="次数"
        />
        <div class="form-tip">
          每个预约记录的最大重试次数
        </div>
      </el-form-item>

      <el-divider>占号策略</el-divider>

      <el-form-item label="启用占号" prop="enable_placeholder">
        <el-switch v-model="form.enable_placeholder" />
        <div class="form-tip">
          占号可以提前占用时段，真实预约时自动释放
        </div>
      </el-form-item>

      <template v-if="form.enable_placeholder">
        <el-form-item label="占号比例" prop="placeholder_ratio">
          <el-slider
            v-model="form.placeholder_ratio"
            :min="0.1"
            :max="1.0"
            :step="0.1"
            :format-tooltip="formatPercentage"
            show-input
          />
          <div class="form-tip">
            占号数据与真实数据的比例，建议0.2-0.5
          </div>
        </el-form-item>

        <el-form-item label="自动释放时间" prop="auto_release_hours">
          <el-input-number
            v-model="form.auto_release_hours"
            :min="1"
            :max="168"
            placeholder="小时"
          />
          <div class="form-tip">
            占号数据超过此时间后自动释放（小时）
          </div>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          取消
        </el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 150px;
}

:deep(.el-slider) {
  margin-left: 12px;
  margin-right: 40px;
}
</style>
